const k = Symbol()

// 上拉加载更多
export const infinite_scroll = {
    inserted(el, binding) {
        const ops = typeof binding.value === 'function'
            ? { callback: binding.value }
            : binding.value
        const {
            callback,
            target = el,
            distance = 30,
            immediate = false,
        } = ops
        let repeat = false
        function scroll(e) {
            const { scrollHeight, scrollTop, clientHeight } = e.target
            if (scrollHeight - scrollTop - clientHeight <= distance) {
                if (repeat) return
                repeat = true
                callback()
            } else {
                repeat = false
            }
        }
        immediate && callback()
        const targetDom = typeof target === 'string'
            ? el.querySelector(target)
            : target
        targetDom.addEventListener('scroll', scroll, true)
        el[k] = scroll
    },
    unbind(el) {
        el.removeEventListener('scroll', el[k], true)
    },
}